package jsu.hx.lost.Controller;

import jakarta.servlet.http.HttpServletRequest;
import jsu.hx.lost.Config.JwtUtil;
import jsu.hx.lost.Model.entity.User;
import jsu.hx.lost.Service.UserService;
import jsu.hx.lost.Model.dto.LoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private UserService userService;  // 注入 UserService
    @Autowired
    private JwtUtil jwtUtil;

        @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 调用 Service 层进行用户验证并生成 JWT Token
            Map<String, Object> tokenInfo = userService.authenticateUser(loginRequest.getPhone(), loginRequest.getPassword());

            User user = userService.getUserByPhone(loginRequest.getPhone()); // 获取用户 ID
// 构建成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "登录成功");
            response.put("token", tokenInfo.get("token"));
            response.put("userId",  tokenInfo.get("userId")); // 返回用户 ID
            response.put("role", tokenInfo.get("role")); // 返回用户角色
            response.put("profileImage", user.getProfileImage());
            response.put("username", user.getUsername());
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
// 捕获用户不存在或密码错误的异常，返回错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
        }
    }
    // AuthController.java
    @GetMapping("/validate")
    public ResponseEntity<?> validateToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        // 检查格式：必须为 "Bearer " 开头且长度大于 7
        if (authHeader != null
                && authHeader.startsWith("Bearer ")
                && authHeader.length() > 7) {
            String token = authHeader.substring(7);
            if (jwtUtil.isTokenValid(token)) {
                return ResponseEntity.ok().build();
            }
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}